package com.anoopsoft

import grails.converters.JSON;

import org.springframework.context.support.DefaultMessageSourceResolvable
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.web.servlet.support.RequestContextUtils as RCU;

class PatronController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	def returnLocale(request){
		def locale = RCU.getLocale(request)
		println locale
		return locale
	}
	
	def success(){
		println "came in success: " + flash.successMsg
		render (view:"/patron/success.gsp")
	}
	//Restful Method. Returns JSON
	def addPatron(){
		def patronInstance = new Patron(params)
		patronInstance.lang = returnLocale(request)
		
		if(patronInstance.validate()){
			try{
			if (patronInstance.save(failOnError: true)) {
				def successMsg = "Patron['${patronInstance.username}', Id: '${patronInstance.id}'] successfully created"
				def msg = [msgType: "success", successMsg: successMsg]
				render msg as JSON
			}
			
			}
			catch(Exception e){
				def msg = [msgType: "exception", msg: "Exception saving Patron[${patronInstance.username}]", err: e.getMessage()]
				render msg as JSON
			}
		}
		else{
			
			def err = []
			patronInstance.errors.allErrors.eachWithIndex{ it, i -> 
				//err +=  [ i  : "Field error in object '" + it.getObjectName() + "' on field '" + it.field +
				//"': rejected value [" + it.rejectedValue + "]; " + it.codes]
				//println  "\n\n\n\n\n $it"
				
				def customMsg =  message(code:  it.codes[-1])
				
				println "\n***** $customMsg"
				println "\n----- ${it.codes} --- ${it.field}"
				err += [ i : "${it.field} : ${customMsg}"]
			}
		
			def msg = [msgType: "valF", msg: "Error(s) validating Patron[${patronInstance.username}]", err: err]
			render msg as JSON
		}

	}
	
	def add(){
		
	}
	
    def index() {
        redirect(action: "list", params: params)
    }

    def list(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        [patronInstanceList: Patron.list(params), patronInstanceTotal: Patron.count()]
    }

    def create() {
        [patronInstance: new Patron(params)]
    }

    def save() {
        def patronInstance = new Patron(params)
		patronInstance.lang = returnLocale(request)
		
        if (!patronInstance.save(flush: true)) {
            render(view: "create", model: [patronInstance: patronInstance])
            return
        }

        flash.message = message(code: 'default.created.message', args: [message(code: 'patron.label', default: 'Patron'), patronInstance.id])
        redirect(action: "show", id: patronInstance.id)
    }
	
	
    def show(Long id) {
        def patronInstance = Patron.get(id)
        if (!patronInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'patron.label', default: 'Patron'), id])
            redirect(action: "list")
            return
        }

        [patronInstance: patronInstance]
    }

    def edit(Long id) {
        def patronInstance = Patron.get(id)
        if (!patronInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'patron.label', default: 'Patron'), id])
            redirect(action: "list")
            return
        }

        [patronInstance: patronInstance]
    }

    def update(Long id, Long version) {
        def patronInstance = Patron.get(id)
        if (!patronInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'patron.label', default: 'Patron'), id])
            redirect(action: "list")
            return
        }

        if (version != null) {
            if (patronInstance.version > version) {
                patronInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                          [message(code: 'patron.label', default: 'Patron')] as Object[],
                          "Another user has updated this Patron while you were editing")
                render(view: "edit", model: [patronInstance: patronInstance])
                return
            }
        }

        patronInstance.properties = params

        if (!patronInstance.save(flush: true)) {
            render(view: "edit", model: [patronInstance: patronInstance])
            return
        }

        flash.message = message(code: 'default.updated.message', args: [message(code: 'patron.label', default: 'Patron'), patronInstance.id])
        redirect(action: "show", id: patronInstance.id)
    }

    def delete(Long id) {
        def patronInstance = Patron.get(id)
        if (!patronInstance) {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'patron.label', default: 'Patron'), id])
            redirect(action: "list")
            return
        }

        try {
            patronInstance.delete(flush: true)
            flash.message = message(code: 'default.deleted.message', args: [message(code: 'patron.label', default: 'Patron'), id])
            redirect(action: "list")
        }
        catch (DataIntegrityViolationException e) {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'patron.label', default: 'Patron'), id])
            redirect(action: "show", id: id)
        }
    }
}
